<template>
  <a-modal v-model:visible="data.modal"   :title="data.option" @cancel="clearFrom" @ok="handleOk">
    <a-form
        :model="categoryFrom"
        ref="formRef"
    >
      <a-form-item has-feedback label="名称" name="name" :rules="formCategoryRules.name">
        <a-input v-model:value="categoryFrom.name" autocomplete="off" />
      </a-form-item>
      <a-form-item has-feedback label="状态" name="checkPass">
        <a-switch v-model:checked="categoryFrom.status" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">

import {reactive, ref, watch} from "vue";
import type { FormInstance } from 'ant-design-vue';
import { message} from "ant-design-vue";
import {Option} from "@/enums/option";
import {adminAddCategory, adminEditCategory} from "@/api/api";
import getCategory from "@/composables/request/category/getCategory";


const props = defineProps(['values']);
const data = ref(props.values);
const emit =  defineEmits(['handleModal']);
const formRef = ref<FormInstance>();

watch(()=> props.values,
    (newVal)=>{
  data.value=newVal;
})
const categoryFrom = reactive<any>({
  name: '',
  status: true,
});
const formCategoryRules = reactive({
  name: [{ required: true, message: '请输入分类名称' }],
});

watch(data.value,async ()=>{
  if(data.value.modal && data.value.option == Option.edit) {
    const  res = await getCategory(data.value.id)
    categoryFrom.name = res.name
    categoryFrom.status = res.status == '1'
  }
})

function  handleOk() {
  formRef.value?.validateFields().then(async () => {
    categoryFrom.status = categoryFrom.status ? '1' : '0'
    if(data.value.option == Option.edit) {
       const res:any = await adminEditCategory(categoryFrom,data.value.id);
       if(res.code != 200) return message.error(res.msg);
    } else if(data.value.option == Option.add) {
      const res:any = await adminAddCategory(categoryFrom);
      if(res.code != 201) return message.error(res.msg);
    }
    message.success(data.value.option + "成功");
    emit("handleModal");
    data.value.modal   = !data.value.modal
    clearFrom();
    formRef.value?.clearValidate();
  }).catch((err:any)=>{
    message.error(err.errorFields[0].errors[0]);
  })
}

function clearFrom(){
  categoryFrom.name = ''
  categoryFrom.status = true
}


</script>

<style lang="less" scoped>

</style>